An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.


In [ ]:
normal_dic = {}
normal_dic['India'] = 'New Delhi'
normal_dic['Afganistan'] = 'Kabul'
normal_dic['Albania'] = 'Tirana'
normal_dic['Austria'] = 'Vienna'
print(normal_dic)

In [ ]:
from collections import OrderedDict
ordered_dic = OrderedDict()
ordered_dic['India'] = 'New Delhi'
ordered_dic['Afganistan'] = 'Kabul'
ordered_dic['Albania'] = 'Tirana'
ordered_dic['Austria'] = 'Vienna'
print(ordered_dic)

A few more operations:
Overwriting:


In [ ]:
ordered_dic['Afganistan'] = 'Athens'
print(ordered_dic)

Deleting:


In [ ]:
del ordered_dic['Albania']
print(ordered_dic)

Inserting again:


In [ ]:
ordered_dic['Albania'] = 'Tirana'
print(ordered_dic)

But why doesn't this work?


In [ ]:
from collections import OrderedDict
ordered_dic = OrderedDict({'India' : 'New Delhi', 'Afganistan' : 
                           'Kabul', 'Albania' : 'Tirana', 
                           'Austria' : 'Vienna'})
print(ordered_dic)